const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 每页显示的条数
const ITEMS_PER_PAGE = 5;

// 中间件：检查用户是否登录
const checkAuth = (req, res, next) => {
    if (!req.session.userId) {
        return res.redirect('/login');
    }
    next();
};

router.use(checkAuth);

// 显示待办事项列表
router.get('/', async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const status = req.query.status || 'all';
        const search = req.query.search || '';

        console.log('查询参数:', { page, status, search });

        // 构建查询条件
        let whereClause = 'WHERE user_id = ?';
        let queryParams = [req.session.userId];

        console.log('用户ID:', req.session.userId);

        if (status !== 'all') {
            whereClause += ' AND status = ?';
            queryParams.push(status);
        }

        if (search) {
            whereClause += ' AND (title LIKE ? OR description LIKE ?)';
            queryParams.push(`%${search}%`, `%${search}%`);
        }

        // 打印SQL查询语句
        const countSql = `SELECT COUNT(*) as total FROM todos ${whereClause}`;
        console.log('计数SQL:', countSql);
        console.log('参数:', queryParams);

        const [countResult] = await db.execute(
            countSql,
            queryParams
        );

        console.log('计数结果:', countResult);

        const total = countResult[0].total;
        const totalPages = Math.ceil(total / ITEMS_PER_PAGE);
        const offset = (page - 1) * ITEMS_PER_PAGE;

        const dataSql = `SELECT * FROM todos ${whereClause} ORDER BY created_at DESC LIMIT ${ITEMS_PER_PAGE} OFFSET ${offset}`;
        console.log('数据SQL:', dataSql);
        console.log('参数:', queryParams);

        const [todos] = await db.execute(
            dataSql,
            queryParams
        );

        console.log('查询到的数据:', todos);

        res.render('todos', {
            todos,
            currentPage: page,
            totalPages,
            status,
            search,
            query: req.query
        });
    } catch (error) {
        console.error('查询出错:', error);
        res.render('todos', {
            todos: [],
            currentPage: 1,
            totalPages: 0,
            status: 'all',
            search: '',
            error: '获取待办事项失败'
        });
    }
});

// 添加待办事项
router.post('/', async (req, res) => {
    try {
        const { title, description } = req.body;

        // 验证标题和描述是否都存在且不为空
        if (!title?.trim() || !description?.trim()) {
            return res.render('todos', {
                todos: [],
                currentPage: 1,
                totalPages: 0,
                status: 'all',
                search: '',
                error: '标题和描述都不能为空！'
            });
        }

        await db.execute(
            'INSERT INTO todos (user_id, title, description) VALUES (?, ?, ?)',
            [req.session.userId, title.trim(), description.trim()]
        );
        res.redirect('/todos');
    } catch (error) {
        console.error('添加失败:', error);
        res.redirect('/todos');
    }
});

// 更新待办事项
router.post('/:id', async (req, res) => {
    try {
        const { status } = req.body;
        // 获取当前页码、状态过滤和搜索条件
        const { page, status: filterStatus, search } = req.query;

        // 先检查当前待办事项的状态
        const [todos] = await db.execute(
            'SELECT status FROM todos WHERE id = ? AND user_id = ?',
            [req.params.id, req.session.userId]
        );

        if (todos.length === 0) {
            return res.redirect(`/todos?page=${page || 1}&status=${filterStatus || 'all'}&search=${search || ''}`);
        }

        // 如果待办事项已完成，则不允许修改状态
        if (todos[0].status === 'completed') {
            return res.redirect(`/todos?page=${page || 1}&status=${filterStatus || 'all'}&search=${search || ''}`);
        }

        // 只允许将状态改为已完成
        if (status !== 'completed') {
            return res.redirect(`/todos?page=${page || 1}&status=${filterStatus || 'all'}&search=${search || ''}`);
        }

        await db.execute(
            'UPDATE todos SET status = ? WHERE id = ? AND user_id = ?',
            ['completed', req.params.id, req.session.userId]
        );
        res.redirect(`/todos?page=${page || 1}&status=${filterStatus || 'all'}&search=${search || ''}`);
    } catch (error) {
        console.error('更新失败:', error);
        res.redirect(`/todos?page=${page || 1}&status=${filterStatus || 'all'}&search=${search || ''}`);
    }
});

// 删除待办事项
router.post('/:id/delete', async (req, res) => {
    try {
        await db.execute(
            'DELETE FROM todos WHERE id = ? AND user_id = ?',
            [req.params.id, req.session.userId]
        );
        res.redirect('/todos');
    } catch (error) {
        res.redirect('/todos');
    }
});

// 显示编辑页面
router.get('/:id/edit', async (req, res) => {
    try {
        const [todos] = await db.execute(
            'SELECT * FROM todos WHERE id = ? AND user_id = ?',
            [req.params.id, req.session.userId]
        );

        if (todos.length === 0) {
            return res.redirect('/todos');
        }

        // 如果待办事项已完成，不允许编辑
        if (todos[0].status === 'completed') {
            return res.redirect('/todos');
        }

        res.render('edit-todo', { todo: todos[0] });
    } catch (error) {
        console.error('获取待办事项失败:', error);
        res.redirect('/todos');
    }
});

// 处理编辑提交
router.post('/:id/edit', async (req, res) => {
    try {
        // 先检查待办事项的状态
        const [todos] = await db.execute(
            'SELECT status FROM todos WHERE id = ? AND user_id = ?',
            [req.params.id, req.session.userId]
        );

        if (todos.length === 0 || todos[0].status === 'completed') {
            return res.redirect('/todos');
        }

        const { title, description } = req.body;
        await db.execute(
            'UPDATE todos SET title = ?, description = ? WHERE id = ? AND user_id = ?',
            [title || '', description || '', req.params.id, req.session.userId]
        );
        res.redirect('/todos');
    } catch (error) {
        console.error('更新失败:', error);
        res.redirect('/todos');
    }
});

module.exports = router; 